from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from database import get_db, engine
from models import Base
from schemas import Furniture, FurnitureCreate, FurnitureUpdate
from crud import create_furniture, get_furniture_list, get_furniture, update_furniture, delete_furniture

# 创建数据库表
Base.metadata.create_all(bind=engine)

# 创建FastAPI应用
app = FastAPI(
    title="家具管理API",
    description="简单的家具CRUD API",
    version="1.0.0"
)

# 1. 创建家具 (CREATE)
@app.post("/furniture/", response_model=Furniture, status_code=201)
def create_furniture_api(furniture: FurnitureCreate, db: Session = Depends(get_db)):
    """创建新家具"""
    return create_furniture(db=db, furniture=furniture)

# 2. 获取家具列表 (READ)
@app.get("/furniture/", response_model=List[Furniture])
def read_furniture_list(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    """获取家具列表"""
    return get_furniture_list(db, skip=skip, limit=limit)

# 3. 根据ID获取家具 (READ)
@app.get("/furniture/{furniture_id}", response_model=Furniture)
def read_furniture(furniture_id: int, db: Session = Depends(get_db)):
    """根据ID获取家具"""
    db_furniture = get_furniture(db, furniture_id=furniture_id)
    if db_furniture is None:
        raise HTTPException(status_code=404, detail="家具不存在")
    return db_furniture

# 4. 更新家具 (UPDATE)
@app.put("/furniture/{furniture_id}", response_model=Furniture)
def update_furniture_api(furniture_id: int, furniture: FurnitureUpdate, db: Session = Depends(get_db)):
    """更新家具信息"""
    db_furniture = update_furniture(db, furniture_id=furniture_id, furniture=furniture)
    if db_furniture is None:
        raise HTTPException(status_code=404, detail="家具不存在")
    return db_furniture

# 5. 删除家具 (DELETE)
@app.delete("/furniture/{furniture_id}", status_code=204)
def delete_furniture_api(furniture_id: int, db: Session = Depends(get_db)):
    """删除家具"""
    success = delete_furniture(db, furniture_id=furniture_id)
    if not success:
        raise HTTPException(status_code=404, detail="家具不存在")

# 根路径
@app.get("/")
def root():
    return {"message": "家具管理API", "docs": "/docs"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)
